<template>
  <div class="product-list" style="padding: 0px;">
    <el-card>
      <el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="客户名称">
          <el-input size="small" v-model="searchForm.customer" placeholder="请输入客户名称" @keyup.enter.native="onSubmit" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="商品名称">
          <el-input size="small" v-model="searchForm.productName" placeholder="请输入商品名称" @keyup.enter.native="onSubmit"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="商品编码">
          <el-input size="small" v-model="searchForm.sku" placeholder="请输入商品编码" @keyup.enter.native="onSubmit"
            clearable></el-input>
        </el-form-item> -->
        <el-form-item label="发货开始日期">
          <div class="block">
            <el-date-picker v-model="searchForm.startDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD" style="width: 100%;" type="date" placeholder="选择发货开始日期"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="发货结束日期">
          <div class="block">
            <el-date-picker v-model="searchForm.endDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD" style="width: 100%;" type="date" placeholder="选择发货结束日期"></el-date-picker>
          </div>
        </el-form-item>

        <el-form-item label="发货单">
          <el-input size="small" v-model="searchForm.deliveryNo" placeholder="请输入发货单" @keyup.enter.native="onSubmit" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="Search" @click="onSubmit">查询</el-button>
          <el-button @click="onReset" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card style="margin-top:5px;">
      <el-button size="small" icon="Plus" @click="addClick" v-auth="'/shipping/btn-add'">新增发货单</el-button>
      <el-button size="small" icon="Download" v-loading="exportLoading" @click="onExport">导出</el-button>

      <el-table size="small" :data="tableData" border style="width: 100%;margin-top:10px;" v-loading="loading">
        <el-table-column prop="deliveryNo" fixed min-width="160" label="发货单号"></el-table-column>
        <el-table-column prop="orderNo" label="销售订单号" min-width="180"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" min-width="180" align="center">
          <template #default="scope">
            <span>
              {{ scope.row.customerName }}
            </span><span>
              ({{ scope.row.customerMobile }})
            </span>

          </template>
        </el-table-column>
        <el-table-column prop="deliveryName" label="发货人" min-width="130" align="center"></el-table-column>
        <el-table-column prop="deliveryCount" label="发货数量" min-width="130" align="center"></el-table-column>
        <el-table-column prop="deliveryAmount" label="发货总金额" min-width="160">
          <template #default="scope">
            ￥{{ scope.row.deliveryAmount || '0.00' }}
          </template>
        </el-table-column>

        <!-- 发货方式 10-快递 20-自提 -->
        <el-table-column prop="deliveryType" label="发货方式" min-width="140">
          <template #default="scope">
            <el-tag type="success">{{ filterTypeName(scope.row.deliveryType) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 20-部分发货 30-全部发货 -->
        <el-table-column prop="deliveryStatus" label="发货状态" min-width="140">
          <template #default="scope">
            <el-tag v-if="scope.row.deliveryStatus" type="success">{{ scope.row.deliveryStatus == '20' ? '全部发货' :
              scope.row.deliveryStatus ==
                '30' ? "部分发货" : "" }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="deliveryTime" label="发货时间" min-width="150" align="center"></el-table-column>
        <el-table-column prop="" label="业务员" min-width="140">
          <template #default="scope">
            {{ scope.row.customerName }}
          </template>
        </el-table-column>
        <el-table-column prop="takeStore" label="自提门店" min-width="140"></el-table-column>
        <el-table-column prop="orderTotalAmount" label="订单总金额" min-width="160">
          <template #default="scope">
            ￥{{ scope.row.orderTotalAmount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="150" align="center"></el-table-column>
        <!-- <el-table-column prop="updateTime" label="更新时间" min-width="130"></el-table-column> -->
        <!-- <el-table-column prop="residueCount" label="剩余数量" min-width="160"></el-table-column> -->
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status == 10 ? '' : 'success'" size="small">{{ scope.row.statusTxt }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <!-- <el-button @click="auditClick(scope.row)" type="text" v-if="scope.row.auditBtn"
              v-auth="'/shipping/btn-edit'" size="small">审核</el-button> -->
            <el-button @click="viewClick(scope.row)" type="text" size="small" v-auth="'/shipping/btn-details'" icon="View">详情</el-button>
            <el-button v-if="scope.row.status == 10" @click="cancelRow(scope.row)" link type="danger" size="small" v-auth="'/shipping/btn-del'" icon="Close">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination style="margin-top:10px;margin-bottom:10px;float:right;" @size-change="handleSizeChange" @current-change="handleCurrentChange" background :current-page="curPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="totalDataNumber"></el-pagination>
    </el-card>
    
    <!-- 新增 -->
    <el-dialog v-model="addTitleShow" :title="addTitle" width="90%" @close="addTitleShow = false"
      :close-on-click-modal="false">
      <add v-if="addTitleShow" @closeDialog="closeDialog" :rowData="rowData" @addSave="addSave"></add>
    </el-dialog>
    <!-- 订单选择页面 -->
    <el-dialog v-model="tableOrderDataShow" :title="'选择订单'" width="90%" @close="tableOrderDataShow = false"
      :close-on-click-modal="false">
      <el-form size="small" :inline="true" :model="tableOrderDataForm" class="demo-form-inline">
        <el-form-item label="提货开始日期">
          <div class="block">
            <el-date-picker v-model="tableOrderDataForm.startDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
              style="width: 100%;" type="date" placeholder="选择提货开始日期"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="提货结束日期">
          <div class="block">
            <el-date-picker v-model="tableOrderDataForm.endDate" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
              style="width: 100%;" type="date" placeholder="选择提货结束日期"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input size="small" @keyup.enter.native="onTableOrderSubmit" clearable v-model="tableOrderDataForm.orderNo"
            placeholder="请输入订单号"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input size="small" v-model="tableOrderDataForm.mobile" placeholder="请输入手机号"
            @keyup.enter.native="onTableOrderSubmit" clearable></el-input>
        </el-form-item>
        <el-form-item label="提货人">
          <el-input size="small" v-model="tableOrderDataForm.keyword" placeholder="请输入提货人"
            @keyup.enter.native="onTableOrderSubmit" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="Search" @click="onTableOrderSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table size="small" :data="tableOrderData" border height="300" style="width: 100%"
        v-loading="tableOrderLoading">
        <el-table-column label="订单号" fixed prop="orderNo" width="200"></el-table-column>
        <el-table-column label="提货人姓名" prop="extractName" width="150"></el-table-column>
        <el-table-column label="提货人手机" prop="extractPhone" width="160"></el-table-column>
        <el-table-column label="提货方式" prop="deliveryTypeText" width="160"></el-table-column>
        <el-table-column label="总价(优惠前)" prop="totalPrice" width="110"></el-table-column>
        <el-table-column label="总价(优惠后)" prop="orderPrice" width="110"></el-table-column>
        <el-table-column label="优惠券抵扣金额" prop="couponMoney" width="130"></el-table-column>
        <el-table-column label="积分抵扣金额" prop="pointsMoney" width="110"></el-table-column>
        <el-table-column label="定金" prop="depositPrice" width="100"></el-table-column>
        <el-table-column label="包装费" prop="packPrice" width="100"></el-table-column>
        <el-table-column label="尾款" prop="finalPrice" width="100"></el-table-column>
        <!-- <el-table-column label="(定金)支付方式" prop="payTypeText" width="110"></el-table-column> -->
        <!-- <el-table-column label="(尾款)支付方式" prop="finalPayTypeText" width="110"></el-table-column> -->
        <el-table-column label="订单类型" prop="orderSourceText" width="100"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="150"></el-table-column>
        <el-table-column label="状态" prop="orderStatusText" width="100"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="goShipGoods(scope.row)"
              v-auth="'/order/order/delivery'">去发货</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 详情查看 -->
    <el-dialog title="发货单详情" v-model="detailsDrawer" width="80%">
      <detail :rowData="rowData" v-if="detailsDrawer"></detail>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog title="发货单审核" v-model="auditFromDrawer" width="30%">
      <el-form :model="auditFrom" ref="auditFrom" label-width="80px" class="demo-form-inline">
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批结果" prop="auditStatus" :rules="[
              { required: true, message: '审批结果不能为空' }
            ]">
              <el-select placeholder="请选择审批结果" v-model="auditFrom.auditStatus">
                <el-option v-for="(item, index) in auditList" :key="index" :label="item.name"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


        </el-row>
        <el-row>

          <el-col :span="24">
            <el-form-item label="审核意见" prop="auditReason" :rules="[
              { required: false, message: '审核意见不能为空' }
            ]">
              <el-input v-model="auditFrom.auditReason" type="textarea" placeholder="请输入审核意见" clearable></el-input>
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="auditFromDrawer = false">取消</el-button>
        <el-button type="primary" :loading="auditSaveLoading" @click="auditSave">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import detail from "./detail.vue";
import PorductApi from '@/api/product.js';
import OrderApi from "@/api/order.js";
import { defaultPageSize } from '@/utils/table.js'
import qs from "qs";
// 新增
import add from "./add.vue"
export default {
  components: {
    add,
    detail
  },
  data() {
    return {
      tableOrderDataForm: {
        orderNo: '',
        mobile: '',
        keyword: ''
      },
      auditSaveLoading: false,
      exportLoading: false,
      auditList: [
        { value: '10', name: '同意' },
        { value: '20', name: '拒绝' },
      ],
      auditFromDrawer: false,
      auditFrom: {},
      detailsDrawer: false,
      rowData: '',
      addTitle: '新增发货单',
      addTitleShow: false,
      tableOrderDataShow: false,
      activeIndex: '0',
      /*是否正在加载*/
      loading: true,
      /*一页多少条*/
      pageSize: 10,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*搜索参数*/
      searchForm: {
        deliveryNo: '',
      },
      productTypes: [
        { name: '快递', value: 10 },
        { name: '自提', value: 20 },
      ],
      /*列表数据*/
      tableData: [],
      tableOrderLoading: false,
      tableOrderData: [],
      /*全部分类*/
      categoryList: [],
      productCount: {},
      productImportShow: false,
      importLoading: false,
      fileList: []
    };
  },
  created() {
    /*获取列表*/
    this.getData();
  },
  methods: {
    // 详情查看
    viewClick(row, type) {
      this.detailsDrawer = true
      this.rowData = row;
      // let self = this;
      // self.$router.push({
      //   path: "/order/shipping/detail",
      //   query: {
      //     orderDeliveryId: row.orderDeliveryId
      //   },
      // });
    },
    auditSave() {
      this.$refs['auditFrom'].validate((valid) => {
        if (valid) {
          this.auditSaveLoading = true;
          this.auditFrom['deliveryFlowId'] = this.rowData.deliveryApplyId
          PorductApi.deliveryAudit(this.auditFrom).then(res => {
            const { code, data } = res;
            if (code == 1) {
              this.auditFromDrawer = false;
              this.getData();
              ElMessage({
                message: '删除成功',
                type: 'success'
              });
            }
            this.auditSaveLoading = false
          }).catch(e => {
            this.auditSaveLoading = false

          })
        }
      });


    },
    onExport() {
      let Params = this.searchForm;
      Params.pageIndex = this.curPage;
      Params.pageSize = this.pageSize;
      this.exportLoading = true;
      OrderApi.deliveryExport(Params).then((res) => {
        this.exportLoading = false;
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        const fdate = new Date();
        const perx = `${fdate.getFullYear()}-${fdate.getMonth() + 1}-${fdate.getDate()}`;
        a.download = perx + "发货单列表.xlsx";
        a.click();
        setTimeout(() => {
          a.remove();
        }, 1000);
      });
    },
    auditClick(row) {
      this.rowData = row;
      this.auditFromDrawer = true;
    },
    closeDialog() {
      this.addTitleShow = false;
      this.tableOrderDataShow = false;
    },

    filterTypeName(value) {
      const item = this.productTypes.find(f => f.value === value)
      if (item)
        return item.name
      return ''
    },
    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.loading = true;
      self.curPage = val;
      self.getData();
    },

    /*每页多少条*/
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },

    /*切换菜单*/
    handleClick(tab) {
      let self = this;
      self.curPage = 1;
      self.getData();
    },
    onTableOrderSubmit() {
      this.tableOrderData = [];
      this.tableOrderLoading = true;
      PorductApi.orderList({ orderStatus: 40, ...this.tableOrderDataForm }, true).then(res => {
        const { code, data } = res;
        this.tableOrderLoading = false
        if (code == 1) {
          this.tableOrderData = data
        }
      }).catch(e => {
        this.tableOrderLoading = false
      })
    },
    /*获取列表*/
    getData() {
      let self = this;
      let Params = self.searchForm;
      Params.pageIndex = self.curPage;
      Params.pageSize = self.pageSize;
      self.loading = true;
      PorductApi.deliveryPage(Params, true)
        .then(res => {
          self.loading = false;
          console.log(res, 'res')
          const { code, data } = res;
          if (code == 1) {

            self.tableData = data.records;
            self.totalDataNumber = data.total;
          }

        })
        .catch(error => {
          self.loading = false;
        });
    },

    /*搜索查询*/
    onSubmit() {
      this.curPage = 1;
      this.getData();
    },
    onReset(){
      this.searchForm.deliveryNo = null;
      this.searchForm.customer = null;
      this.searchForm.startDate = null;
      this.searchForm.endDate = null;
      this.curPage = 1;
      this.getData();
    },
    // 订单选择页面
    goShipGoods(row) {
      this.addTitle = '新增发货单'
      this.addTitleShow = true;
      this.rowData = row;
    },
    addSave() {
      this.rowData = null;
      this.addTitleShow = false;
      this.tableOrderDataShow = false;
      this.getData();
    },
    /*打开添加*/
    addClick() {
      // 先打开订单选择
      this.tableOrderDataShow = true;
      this.tableOrderLoading = true;
      this.tableOrderDataForm = {
        orderNo: '',
        mobile: '',
        keyword: ''
      }
      // orderStatus 40 待发货
      PorductApi.orderList({ orderStatus: 40 }).then(res => {
        const { code, data } = res;
        this.tableOrderLoading = false
        if (code == 1) {
          this.tableOrderData = data
        }
      })

    },
    // 导出商品
    exportClick() {
      PorductApi.exportProduct()
        .then(res => {
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          const fdate = new Date()
          const perx = `${fdate.getFullYear()}-${fdate.getMonth() + 1}-${fdate.getDate()}`
          a.download = perx + '商品列表.xlsx'
          a.click()
          setTimeout(() => {
            a.remove()
          }, 1000)
        })
    },
    importClick() {
      this.productImportShow = true
    },
    importCancle() {
      this.fileList = []
      this.productImportShow = false
    },

    /*打开编辑*/
    editClick(row) {
      console.log(row);
      this.addTitleShow = true;
      this.rowData = row
      this.addTitle = '编辑发货单'
    },

    /*删除*/
    delClick: function (row) {
      let self = this;
      let msg = '';
      if (row.productStatus == 30) {
        msg = '删除后不可恢复，确认删除该记录吗?';
      } else {
        msg = '删除后将移动到回收站，确定删除该记录吗?';
      }
      ElMessageBox.confirm(msg, '提示', {
        type: 'warning'
      })
        .then(() => {
          PorductApi.delProduct({
            productId: row.productId
          }).then(data => {
            ElMessage({
              message: '删除成功',
              type: 'success'
            });
            self.getData();
          });
        });
    },

    /*取消*/
    cancelRow: function (row) {
      let self = this;

      PorductApi.deliveryCancel({
        deliveryFlowId: row.orderDeliveryId
      }).then(data => {
        ElMessage({
          message: '取消成功',
          type: 'success'
        });
        self.getData();
      });

    },

  }
};
</script>

<style scoped>

::v-deep(.el-scrollbar__bar.is-horizontal) {
  height: 20px;          /* 想多粗就写多大 */
}
</style>
